import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Solution16 {
    public static void main(String[] args) {
        int a = threeSum(new int[]{-1, 2, 1, -4}, 1);
        System.out.println(a);
    }

    public static int threeSum(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        int result = Integer.MAX_VALUE;
        for (int i = 0; i < nums.length; i++) {
            int num1 = nums[i];
            int l = i +1;
            int r = len -1;
            while (l < r){
                int num2 = nums[l];
                int num3 = nums[r];
                int sum = num1 + num2 + num3;
                int sub = sum - target;
                if (sub<0){
                    l++;
                }else if (sub>0){
                    r--;
                }else return 0;
                if (Math.abs(sub)<Math.abs(result-target)) {
                    result = sum;
                }
            }
        }
        return result;
    }
}
